package com.ogawa.joypal.user.activity

import android.annotation.SuppressLint
import android.os.Build
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.ogawa.base.base.BaseVMActivity
import com.ogawa.base.utils.*
import com.ogawa.base.utils.TimeUtils.*
import com.ogawa.base.utils.imageloader.ImageConfigImpl
import com.ogawa.base.utils.imageloader.ImageLoader
import com.ogawa.projectcommon.constants.UrlPathConstant
import com.ogawa.joypal.user.R
import com.ogawa.joypal.user.bean.PutUserInfoRequest
import com.ogawa.joypal.user.dialog.ChangeNameDialog
import com.ogawa.joypal.user.viewmodel.UserInfoEditViewModel
import com.ogawa.joypal.user.widget.DatePickDialog
import com.ogawa.joypal.user.widget.ValuePickDialog
import com.ogawa.projectcommon.constants.Constant
import com.ogawa.projectcommon.utils.ConstantStringUtils
import com.ogawa.projectcommon.utils.ProjectSpUtils
import kotlinx.android.synthetic.main.activity_user_info_edit.*


@Route(path = UrlPathConstant.ACTIVITY_USER_EDIT_INFO)
class UserInfoEditActivity : BaseVMActivity<UserInfoEditViewModel>() {

    override fun getLayoutId(): Int {
        return R.layout.activity_user_info_edit
    }

    override fun initView() {
        super.initView()
        setTitle(getString(R.string.user_edit_info))
        onclickInit()
        val userInfo = ProjectSpUtils.getUserInfo()
        if (userInfo != null) {
            mViewModel.userInfo("${userInfo.user.id}")
        }
    }

    override fun providerVMClass(): Class<UserInfoEditViewModel>? {
        return UserInfoEditViewModel::class.java
    }

    @SuppressLint("SetTextI18n")
    override fun observeVM() {
        mViewModel.putUserInfoState.observe(this, Observer {
            if (it == Constant.SUCCESS) {
                ToastUtils.showShort(getString(R.string.save_success))
//                finish()
                return@Observer
            }
        })
        mViewModel.mUserInfosBean.observe(this, Observer {
            it?.run {
                ImageLoader.getInstance().loadImage(
                    mActivity, ImageConfigImpl
                        .builder()
                        .isCircle(true)
                        .url(it.avatar)
                        .imageView(headIv)
                        .build()
                )
                nameEt.text = printNoNull(it.nickName)
                sexTv.text = ConstantStringUtils.getSex(it.sex)
                birthdayTv.text = getDateToString(it.birthDate)
                heightTv.text = printNoNull(it.height) + "cm"
                widgetTv.text = printNoNull(it.weight) + "kg"
                toleranceTv.text = ConstantStringUtils.getTolerance(it.tolerance)


                mViewModel.mPutUserInfoRequest = PutUserInfoRequest()

                mViewModel.mPutUserInfoRequest.userId = it.id
                mViewModel.mPutUserInfoRequest.nickName =
                    if (it.nickName != null) "${it.nickName}" else ""
                mViewModel.mPutUserInfoRequest.sex = "${it.sex}"
                mViewModel.mPutUserInfoRequest.height = "${it.height}"
                mViewModel.mPutUserInfoRequest.weight = "${it.weight}"
                mViewModel.mPutUserInfoRequest.birthDate = it.birthDate
                mViewModel.mPutUserInfoRequest.massageExperience = "${it.massageExperience}"
                mViewModel.mPutUserInfoRequest.tolerance = "${it.tolerance}"
                mViewModel.mPutUserInfoRequest.image = "${it.image}"
            }


        })
        mViewModel.requestUserBean.observe(this, Observer {

        })
    }

    private fun onclickInit() {
        chooseHeadImgLL.setOnClickListener {
            PictureSelector.create(mActivity)
                .openGallery(PictureMimeType.ofImage()) // 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .imageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(1) // 最大图片选择数量
                .minSelectNum(1) // 最小选择数量
                .imageSpanCount(4) // 每行显示个数
                .selectionMode(PictureConfig.SINGLE) // 多选 or 单选
                .previewImage(true) // 是否可预览图片
                .isCamera(true) // 是否显示拍照按钮
                .isZoomAnim(true) // 图片列表点击 缩放效果 默认true
                .enableCrop(true) // 是否裁剪
                .compress(true) // 是否压缩
                .synOrAsy(true) //同步true或异步false 压缩 默认同步
                .glideOverride(160, 160) // glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .freeStyleCropEnabled(true) // 裁剪框是否可拖拽
                .minimumCompressSize(100) // 小于100kb的图片不压缩
//                .forResult(PictureConfig.CHOOSE_REQUEST) //结果回调onActivityResult code
                .forResult(object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(selectList: MutableList<LocalMedia>?) {
                        try {
                            var path = selectList!![0].compressPath
                            if (path == null || path.isEmpty()) {
                                if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
                                    path = selectList!![0].androidQToPath
                                } else {
                                    path = selectList!![0].realPath
                                }
                            }
                            if (path == null || path.isEmpty()) {
                                ToastUtils.showShort(getString(R.string.fail_read_image))
                                return
                            }
                            LogUtils.e("当前选择的：${path}")
                            mViewModel.mPutUserInfoRequest.image = AppUtil.imageToBase64(path)
                            if (mViewModel.mPutUserInfoRequest.image == null || mViewModel.mPutUserInfoRequest.image.isEmpty()) {
                                ToastUtils.showShort(getString(R.string.fail_read_image))
                                return
                            }
                            val userInfo = ProjectSpUtils.getUserInfo()
                            userInfo.img = AppUtil.imageToBase64(path)
                            ProjectSpUtils.setUserInfo(userInfo)
                            saveInfoBean()
                            ImageLoader.getInstance().loadImage(
                                mActivity, ImageConfigImpl
                                    .builder()
                                    .isCircle(true)
                                    .url(path)
                                    .imageView(headIv)
                                    .build()
                            )
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }

                    override fun onCancel() {
                    }

                })
        }
        nameLL.setOnClickListener {
            ChangeNameDialog().show(
                mActivity,
                nameEt.text.toString(),
                object : ChangeNameDialog.ChangeNameDialogListener {
                    override fun successOnclick(newName: String) {
                        if (isEmptyStr(newName)) {
                            ToastUtils.showShort(getString(R.string.please_input_name))
                            return
                        }
                        mViewModel.mPutUserInfoRequest.nickName = newName
                        nameEt.setText(newName)
                        saveInfoBean()
                    }
                })
        }
        selectSexLL.setOnClickListener {
            var mDialog = ValuePickDialog(this, ValuePickDialog.GENDER)
            mDialog.setTvSaveOnClickListener { _ ->
                val sex = (mDialog.valueIndex + 1) % 2
                var gender = mDialog.value
                sexTv.text = gender
                mDialog.dismiss()
                mViewModel.mPutUserInfoRequest.sex = "$sex"
                saveInfoBean()
            }
            mDialog!!.show()
        }
        selectBirthdayLL.setOnClickListener {
            var mDialog = DatePickDialog(this)
            mDialog.setTvSaveOnClickListener { _ ->
                val year = mDialog.year
                val month = mDialog.month
                val day = mDialog.day
                birthdayTv.text = printDateStr("$year", "$month", "$day")
                var birLong = ydmTo13Long("$year", "$month", "$day")
                mViewModel.mPutUserInfoRequest.birthDate = birLong
                saveInfoBean()

                mDialog.dismiss()
            }
            mDialog.show()
        }
        heightLL.setOnClickListener {
            var mDialog = ValuePickDialog(this, ValuePickDialog.HEIGHT)
            mDialog.setTvSaveOnClickListener { _ ->
                val height = (mDialog.value)
                heightTv.setText("${height}cm")
                mViewModel.mPutUserInfoRequest.height = height
                mDialog.dismiss()
                saveInfoBean()
            }
            mDialog.show()
        }
        widgetLL.setOnClickListener {
            var mDialog = ValuePickDialog(this, ValuePickDialog.WEIGHT)
            mDialog.setTvSaveOnClickListener { _ ->
                val value = (mDialog.value)
                widgetTv.setText("${value}kg")
                mViewModel.mPutUserInfoRequest.weight = value
                saveInfoBean()
                mDialog.dismiss()
            }
            mDialog.show()
        }
        toleranceLL.setOnClickListener {
            var mDialog = ValuePickDialog(this, ValuePickDialog.SUFFER)
            mDialog.setTvSaveOnClickListener { _ ->
                val value = (mDialog.value)
                toleranceTv.text = value
                mViewModel.mPutUserInfoRequest.tolerance = "${mDialog.valueIndex + 1}"
                saveInfoBean()
                mDialog.dismiss()
            }
            mDialog.show()
        }

        tvSave.setOnClickListener {
            val niceName = nameEt.text.toString()
            if (isEmptyStr(niceName)) {
                ToastUtils.showShort(getString(R.string.please_input_name))
                return@setOnClickListener
            }
            mViewModel.mPutUserInfoRequest.image = ProjectSpUtils.getUserInfo().img
            mViewModel.mPutUserInfoRequest.nickName = niceName
            saveInfoBean()
        }
    }


    fun saveInfoBean() {
        mViewModel.mPutUserInfoRequest.image = ProjectSpUtils.getUserInfo().img
        mViewModel.putUserInfo()
    }

}